<template>
  <el-dialog
    title="新增目录"
    :visible.sync="dialogVisible"
    width="30%"
    :before-close="handleClose"
  >
    <!-- 表单区域 -->
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
    >
      <el-form-item label="所属学科" prop="region">
        <el-select
          style="width: 100%"
          v-model="ruleForm.subjectID"
          placeholder="请选择"
        >
          <el-option
            v-for="(item, index) in value"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item width="80px" label="目录名称" prop="tagName">
        <el-input v-model="ruleForm.tagName"></el-input>
      </el-form-item>
    </el-form>
    <!-- 表单区域 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>

      <el-button type="primary" @click="determine('ruleForm')">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { add, update } from "@/api/hmmm/tags";
import { simple } from "@/api/hmmm/subjects";
export default {
  props: ["dialogVisible", "updateData"],
  created() {
    window.location.search.href;
    this.$route.query;
    // 获取下拉框数据
    this.getSelect();
  },
  watch: {
    updateData(newv) {
      if (newv) {
        this.btnStatus = "update";
        this.ruleForm.subjectID = newv.subjectID;
        this.ruleForm.tagName = newv.tagName;
      } else {
        this.btnStatus = "add";
        this.ruleForm = {
          subjectID: "",
          tagName: "",
        };
      }
    },
  },
  data() {
    return {
      // 表单绑定
      ruleForm: {
        subjectID: "",
        tagName: "",
      },
      // 表单验证
      rules: {
        tagName: [
          { required: true, message: "请输入标签名称", trigger: "blur" },
        ],
      },
      // 下拉框选项
      value: null,
      // 按钮类型  新增 add  编辑 update
      btnStatus: "add",
    };
  },
  methods: {
    // 获取下拉框数据
    async getSelect() {
      const { data: res } = await simple();
      console.log(res);
      this.value = res;
    },
    // 关闭对话框组件
    handleClose() {
      console.log(1);
      this.$emit("handleClose");
    },
    // 点击对话框确定按钮触发事件
    determine(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          console.log(this.btnStatus);
          if (this.btnStatus === "add") {
            const { data: res } = await add(this.ruleForm);
            // 确定后直接关闭对话组件
            this.$emit("handleOk");
          } else {
            // 编辑
            this.ruleForm.id = this.updateData.id;
            const { data: res } = await update(this.ruleForm);
            // 确定后直接关闭对话组件
            this.$emit("handleOk");
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style scoped lang='less'></style>
